<template>
  <div>
    <el-button type="primary" style="display: block; margin-left: 0; text-align: left;" @click="handleAdd">新增</el-button>
    <el-table
      :data="tableData"
      style="width: 100%;"
      :default-sort="{ prop: 'date', order: 'descending' }">
      <el-table-column prop="id" label="ID" sortable width="70"></el-table-column>
      <el-table-column prop="name" label="姓名" sortable width="80"></el-table-column>
      <el-table-column prop="sex" label="性别" width="80"></el-table-column>
      <el-table-column prop="age" label="年龄" sortable width="90"></el-table-column>
      <el-table-column prop="email" label="邮件" width="200"></el-table-column>
      <el-table-column prop="tel" label="手机号" width="180"></el-table-column>

      <el-table-column align="left">
        <template #default="scope">
          <!-- 编辑按钮 -->
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)" :icon="Edit">修改</el-button>
          <!-- 删除按钮 -->
          <el-button
            size="small"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
            :icon="Delete">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-model="isFormVisible" title="信息修改">
      <el-form ref="form" :model="editedItem" label-width="70px" id="myForm">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="editedItem.name"></el-input>
        </el-form-item>
        <el-form-item label="邮件" prop="email">
          <el-input v-model="editedItem.email"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="editedItem.sex">
            <el-radio label="男"></el-radio>
            <el-radio label="女"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model="editedItem.age"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="tel">
          <el-input v-model="editedItem.tel"></el-input>
        </el-form-item>
        <el-button type="primary" round @click="submitForm" style="width: 180px;">提交</el-button>
      </el-form>
    </el-dialog>

    <el-dialog v-model="dialogVisible1" title="个人信息">
      <el-form ref="form" :model="formData" label-width="80px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="formData.name"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="formData.sex" placeholder="请选择性别">
            <el-option label="男" value="男"></el-option>
            <el-option label="女" value="女"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model="formData.age"></el-input>
        </el-form-item>
        <el-form-item label="电话号码" prop="tel">
          <el-input v-model="formData.tel"></el-input>
        </el-form-item>
        <el-form-item label="邮件" prop="email">
          <el-input v-model="formData.email"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible1 = false">取消</el-button>
          <el-button type="primary" @click="submitForm1">提交</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Edit, Delete } from '@element-plus/icons-vue';
import axiosInstance from '../service/baseService'; // 替换为axiosInstance文件

const tableData = ref([]);
const isFormVisible = ref(false);
const dialogVisible1 = ref(false);
const editedItem = reactive({
  name: '',
  email: '',
  sex: '',
  age: '',
  tel: ''
});
const formData = reactive({
  name: '',
  sex: '',
  age: '',
  tel: '',
  email: ''
});

let nextId = 1; // 用于生成下一个唯一 ID

onMounted(() => {
  fetchData();
});

const fetchData = async () => {
  try {
    const response = await axiosInstance.get('/select');
    console.log("查询格式");
    console.log(response);
    console.log(response.data);
    console.log("================")
    tableData.value = response.data;
  } catch (error) {
    console.error(error);
  }
};

const handleEdit = (index, row) => {
  Object.assign(editedItem, row); // 复制当前行数据到 editedItem
  isFormVisible.value = true;
};

const handleDelete = async (index, row) => {
  const result = await ElMessageBox.confirm('确定要删除吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  });

  if (!result) return;

  const data = {
    id: Object.values(row)[0]
  };

  try {
    const response = await axiosInstance.post('/delete',data);
    console.log("查询格式");
    console.log(response);
    console.log(response.data);
    console.log("================")
    await fetchData();
  } catch (error) {
    console.error(error);
  }
};

const submitForm = async () => {
  const result = await ElMessageBox.confirm('确定要提交吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  });

  if (!result) return;

  try {
    const response = await axiosInstance.post('/update',editedItem);
    console.log("修改格式");
    console.log(response);
    console.log(response.data);
    console.log("================")
    // await axios.post('http://localhost:8081/update', editedItem);
    await fetchData();
    ElMessage({
      message: "修改成功",
      type: 'success',
      duration: 2000
    });
    isFormVisible.value = false;
    // 清空 editedItem 对象中的数据
    Object.keys(editedItem).forEach(key => (editedItem[key] = ''));
  } catch (error) {
    console.error(error);
  }
};

const submitForm1 = async () => {
  try {
    // 首先将新数据添加到 tableData 数组中
    tableData.value.push({
      id: getNextId(),
      ...formData,
    });

    // 然后向服务器发送数据
    const response = await axiosInstance.post('/insert',formData);
    // const response = await axios.post('http://localhost:8081/insert', formData);
    console.log("增加模式");
    console.log(response);
    console.log(response.data);
    console.log("================")
    
    // 可以选择性地重新获取数据以保持同步
    await fetchData();

    ElMessage({
      message: "增加成功",
      type: 'success',
      duration: 2000
    });
    dialogVisible1.value = false;
    // 清空 form 对象中的数据
    Object.keys(formData).forEach(key => (formData[key] = ''));
  } catch (error) {
    console.error(error);

    // 如果服务器端出现错误，从 tableData 中移除未成功提交的数据
    tableData.value.pop();
    ElMessage({
      message: "增加失败，请检查网络或稍后再试。",
      type: 'error',
      duration: 2000
    });
  }
};

const handleAdd = () => {
  // 清空 form 对象中的数据
  Object.keys(formData).forEach(key => (formData[key] = ''));
  dialogVisible1.value = true;
};

// 生成下一个唯一 ID
const getNextId = () => {
  return nextId++;
};
</script>

<style scoped>
/* 表单样式 */
.el-form {
  width: 300px; /* 设置表单宽度 */
  height: 400px; /* 设置表单高度 */
  margin: 0 auto; /* 将表单水平居中 */
}

/* 对话框样式 */
.el-dialog {
  width: 400px; /* 设置对话框宽度 */
  height: 600px; /* 设置对话框高度 */
  text-align: center; /* 对话框标题居中 */
}

.search-container {
  display: flex;
  justify-content: space-between;
  flex-direction: row;
}

.dialog-footer {
  display: flex;
  justify-content: center;
}
</style>